'use strict';
const db = uniCloud.database()
const dbCmd = db.command
exports.main = async (event, context) => {
	if (event.leixing == 1) {
		const res = await db.collection('lipinka').where({
			kahao: event.kahao,
			mima: event.mima,
			kazhuangtai: 1,
			shengyu: dbCmd.gt(0)
		}).field({
			next_duihuantime: true // 修正为对象格式‌:ml-citation{ref="6,8" data="citationList"}
		}).get()
		return res
	} else if (event.leixing == 2) {
		const res1 = await db.collection('lipinka').where({
			kahao: event.shuju.kahao,
			mima: event.shuju.mima,
			kazhuangtai: 1,
			shengyu: dbCmd.gt(0)
		}).update({
			shengyu: dbCmd.inc(-1),
			shiyong: dbCmd.inc(1),
			next_duihuantime: event.next_duihuantime

		})
		const res = await db.collection('duihuanlist').add(event.shuju)
		return res
	} else if (event.leixing == 3) {
		// 从lipinka中查询kahao在event.kahao数组中的数据,返回字段为kahao和mima
		const res = await db.collection('lipinka').where({
			kahao: dbCmd.in(event.kahao)
		}).field({
			kahao: true,
			kazhuangtai: true,
			shengyu: true,
			youxiaoqi: true,
			next_duihuantime: true,
			leixing: true
		}).get()
		return res
	} else if (event.leixing == 4) {
		const res = await db.collection('lipinka').where(event.tiaojian).orderBy('kahao','asc').field(event.field).skip(event.skip).limit(event.limit).get()
		return res
	}else if (event.leixing == 5) {
		// 从lipinka中查询kahao在event.kahao数组中的数据,返回字段为kahao和mima
		const res = await db.collection('lipinka').where({
			kahao: dbCmd.in(event.kahao),
			kazhuangtai:0,
			user_id:event.user_id
		}).field({
			kahao: true,
			youxiaoqi: true,
			next_duihuantime: true,
			price:true,
			leixing: true,
			leixing_id:true
		}).get()
		return res
	}else if (event.leixing == 6) {
		const res = await db.collection('duihuanlist').aggregate()
		 .match({ status: event.status })
		  .lookup({
		    from: 'lipinka',
		    localField: 'kahao',
		    foreignField: 'kahao',
		    as: 'lipinka_data'
		  })
		  .addFields({
		    lipinka: { 
		      $map: {
		        input: "$lipinka_data",
		        in: {
		          kahao: "$$this.kahao",
		          kazhuangtai: "$$this.kazhuangtai",
		          youxiaoqi: "$$this.youxiaoqi",
				  leixing: "$$this.leixing",
				  price: "$$this.price",
		          next_duihuantime: "$$this.next_duihuantime",
		          shengyu: "$$this.shengyu",
		          shiyong: "$$this.shiyong"
		        }
		      }
		    }
		  })
		  .project({
		    lipinka_data: 0  
		  })
		  .end()
		return res
	}else if (event.leixing == 7) {
		const res = await db.collection('duihuanlist').where(event.tiaojian).update(event.shuju)
		return res
	}else if (event.leixing == 8) {
		const res = await db.collection('lipinka_xinghao_zhekou').where(event.tiaojian).get()
		return res
	}
};